/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package bgu.sonar.util.ui.sat;

import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
import javax.swing.SwingUtilities;
import org.openide.windows.Mode;
import org.openide.windows.TopComponent;
import org.openide.windows.WindowManager;

/**
 *
 * @author bennyl
 */
public class SatellitsManager {

    Set<HasSatellites> sats = new HashSet<>();
    boolean syncing = false;

    public void onNewWindowActivated() {
        sync();
    }

    public void onNewWindowOpened() {
        sync();
    }

    public void onWindowClosed() {
        sync();
    }

    public void sync() {
        if (syncing) {
            return;
        }

        if (!SwingUtilities.isEventDispatchThread()) {
            throw new RuntimeException("Must Handle satellites in event dispatching thread.");
        }

        syncing = true;
        for (Iterator<HasSatellites> it = sats.iterator(); it.hasNext();) {
            HasSatellites s = it.next();
            TopComponent ts = (TopComponent) s;
            if (!ts.isShowing()) {
                for (Satallites.Satalite satellite : s.getSatellites().list()) {
                    satellite.tc.close();
                }

                it.remove();
            }
        }

        for (TopComponent top : WindowManager.getDefault().getRegistry().getOpened()) {
            if (top.isShowing() && top instanceof HasSatellites && !sats.contains(top)) {
                final HasSatellites hassat = (HasSatellites) top;
                sats.add(hassat);
                for (Satallites.Satalite satellite : hassat.getSatellites().list()) {
                    if (!satellite.tc.isOpened()) {
                        System.out.println("satelite manager openning " + satellite.tc.getClass().getSimpleName());
                        if (satellite.mode != null) {
                            final Mode mode = WindowManager.getDefault().findMode(satellite.mode);
                            if (mode == null) {
                                System.err.println("could not doc into " + satellite.mode + " mode not exists.. ");
                            } else {
                                mode.dockInto(satellite.tc);
                            }
                        }
                        satellite.tc.open();
                    }

                    satellite.tc.requestVisible();
                    satellite.tc.setVisible(true);
                }
            }
        }

        syncing = false;

    }
}
